package algorithm.leetcode.simple;

/*
 给定两个数组，编写一个函数来计算它们的交集
 */

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-11-07
 */
public class Question349 {

    public static void main(String[] args) {
        Question349 question = new Question349();
        int[] nums1 = {1,2,2,1};
        int[] nums2 = {2,2};
        int[] ints = question.intersection(nums1, nums2);
        System.out.println(Arrays.toString(ints));
    }

    public int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        Set<Integer> set = new HashSet<>();
        int i1 = 0;
        int i2 = 0;
        while (i1 < nums1.length && i2 < nums2.length) {
            int n1 = nums1[i1];
            int n2 = nums2[i2];
            if (n1 == n2) {
                set.add(n1);
                while (i1 < nums1.length && n1 == nums1[i1]) {
                    i1++;
                }
                while (i2 < nums2.length && n2 == nums2[i2]) {
                    i2++;
                }
            } else if (n1 < n2) {
                i1++;
            } else {
                i2++;
            }
        }
        int[] res = new int[set.size()];
        Iterator<Integer> iterator = set.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            res[index++] = iterator.next();
        }
        return res;
    }
}
